package com.ita.servlet.merchant;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.camel.util.jsse.ClientAuthentication;

import com.ita.factory.MServiceFactory;
import com.ita.httpclient.CheckClient;
import com.ita.pojo.MenuType;
import com.ita.pojo.Merchant;
import com.ita.service.MenuService;
import com.ita.service.MerchantService;
import com.ita.util.Constant;
import com.ita.util.State;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private MerchantService mService;
	private MenuService fService;

	public LoginServlet() {
		mService = MServiceFactory.getMerchantService();
		fService = MServiceFactory.getMenuService();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");	

		
		
		Merchant m = mService.loadMerchant(name);

		if (m == null) {
			request.setAttribute("name_error", Constant.NAMEERROR);
			request.getRequestDispatcher("login.jsp")
					.forward(request, response);
			return;
		}

		if (m.getPassword().equals(pwd)) {

			CheckClient client = new CheckClient(m.getId());
			State s = client.getState();
//			State s = State.PASS;
			m = mService.loadMerchant(name);
			request.getSession().setAttribute("m", m);
			if (s == State.BLOCK) {
				request.getSession().setAttribute("m_state", "Blocked");
				response.sendRedirect("block.jsp");
				return;
			}
			if (s == State.FAIL) {
				request.getSession().setAttribute("m_state", "Check Fail");
				request.getSession().setAttribute("msg",Constant.REASON);
//				response.sendRedirect("sec/info.jsp");
				response.sendRedirect("info");
				return;
			}

			if (s == State.DEFAULT) {
				request.getSession().setAttribute("m_state", "Unhandle");
//				response.sendRedirect("sec/info.jsp");
				response.sendRedirect("info");
				return;
			}
			if (s == State.ERROR) {
				response.sendRedirect("error.jsp");
				return;
			}

			if (s == State.PASS) {
				List<MenuType> foodTypes = fService.loadMenuType();

				request.getSession().setAttribute("food_type", foodTypes);
				request.getSession().setAttribute("m_state", "Success");
				
				response.sendRedirect("sec/menu/manager.jsp");
				return;
			
//				request.getRequestDispatcher("food").forward(request, response);
			}

		} else {
			request.setAttribute("pwd_error", Constant.PWDERROR);
			request.getRequestDispatcher("login.jsp")
					.forward(request, response);
		}

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
